#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/12/31 22:08
# @Author : George
import asyncio
import requests
import time
import aiohttp
from threading import currentThread

"""
async def request(url): # 耗时： 9.054526805877686,requests是同步阻塞，必须替换为异步库提供的函数aiohttp
"""

urls = [
    "http://127.0.0.1:5000/jar",
    "http://127.0.0.1:5000/bobo",
    "http://127.0.0.1:5000/test"
]

start = time.time()


# 耗时： 9.054526805877686,requests是同步操作
# async def request(url):
#     print("开始下载", url)
#     response = requests.get(url=url)
#     print(response.text)
#     print("下载结束", url)
#     print("------------")

async def request_2(url):
    print("开始下载", url, currentThread())
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
        "Referer": "https://movie.douban.com/explore"
    }
    # 设置代理
    proxy = "http://8.220.204.215:8008"

    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers) as response:
            text = await response.text()
            print(text)
    print("下载结束", url)


async def main():
    tasks = []
    for url in urls:
        tasks.append(asyncio.create_task(request_2(url)))
    await asyncio.wait(tasks)


asyncio.run(main())

end = time.time()
print("耗时：", end - start)
